package org.liaohailong.library.widget.ptr;

import android.view.View;
import android.widget.Scroller;

import androidx.annotation.NonNull;

/**
 * Author: Victor
 * Date: 2019/5/9 10:32
 * Description: 下拉刷新任务执行
 */
class PullToRefreshHandler {
    /**
     * 滑动View
     */
    private View scrollView;

    /**
     * 滑动恢复工具类
     */
    private Scroller scroller;

    /**
     * 最大下拉距离
     */
    private int maxPullDownDistance;

    /**
     * 滑动至触发刷新的距离
     */
    private int refreshDistance = 0;

    PullToRefreshHandler(@NonNull View scrollView) {
        this.scrollView = scrollView;
        scroller = new Scroller(scrollView.getContext());
    }

    void setMaxPullDownDistance(int maxPullDownDistance) {
        this.maxPullDownDistance = maxPullDownDistance;
    }

    void setRefreshDistance(int refreshDistance) {
        this.refreshDistance = refreshDistance;
    }

    void abortScroll() {
        scroller.forceFinished(true);
        scroller.abortAnimation();
    }

    void movePos(int distance, boolean pullDown) {
        int scrollY = scrollView.getScrollY();
        int yOffset = pullDown ? -distance : distance;
        int y = scrollY + yOffset;
        y = Math.max(-maxPullDownDistance, y);
        y = Math.min(0, y);
        scrollView.scrollTo(0, y);
    }

    void showContent() {
        int scrollY = scrollView.getScrollY();
        scroller.startScroll(0, scrollY, 0, Math.abs(scrollY));
        scrollView.postInvalidate();
    }

    void showHeader() {
        int scrollY = scrollView.getScrollY();
        int yOffset = Math.abs(scrollY) - Math.abs(refreshDistance);
        scroller.startScroll(0, scrollY, 0, yOffset);
        scrollView.postInvalidate();
    }

    boolean computeScroll() {
        if (scroller.computeScrollOffset()) {
            int currX = scroller.getCurrX();
            int currY = scroller.getCurrY();
            scrollView.scrollTo(currX, currY);
            scrollView.postInvalidate();
            return true;
        }

        return false;
    }

    public int getScrollDistance() {
        return Math.abs(scrollView.getScrollY());
    }
}
